package com.jh.paymentchannel.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.MD5;
import com.jh.paymentchannel.util.Util;


@Service
public class ELongTopupRequest  implements TopupRequest{

	private static final Logger log = LoggerFactory.getLogger(ELongTopupRequest.class);
	
	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;
	
	@Autowired
	private BranchbankBussiness branchbankBussiness;
	
	@Autowired
	private Util util;
	
	@Value("${elong.merid}")
	public   String customerid;
	
	@Value("${elong.nkey}")
	private  String nkey;
	
	@Value("${elong.url}")
	private  String sendurl;
	
	
	@Override
	public Map<String, String> topupRequest(HttpServletRequest request,
			String amount, String ordercode, String orderdesc, String extra,
			String notifyurl, String returnurl, String channelParam)
			throws Exception {
		Map<String, String>  map = new HashMap<String, String>();
		RestTemplate restTemplate = new RestTemplate();
		String url = new String();
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		try {
			
		restTemplate=new RestTemplate();
		requestEntity  = new LinkedMultiValueMap<String, String>();
		//版本号
		requestEntity.add("version", "VERSION_2.0");
		//商户ID
		requestEntity.add("customerid",customerid);
		//商户流水号
		requestEntity.add("orderNumber", ordercode);
		//订单金额
		requestEntity.add("ordermoney", amount);
		//通道代码
		requestEntity.add("cardNo", "wxpay" );
		
		String signData="customerid="+customerid+"&orderNumber="+ordercode+"&key="+nkey+"";
		//MD5签名
		requestEntity.add("sign", MD5.MD5EncodeGBK(signData).toUpperCase());
//		requestEntity.add("sign", MD5("customerid={"+customerid+"}&orderNumber={"+ordercode+"}&key={"+nkey+"}").toUpperCase());
		//支付扩展标志
		requestEntity.add("postType", "1");
		//返回地址
		requestEntity.add("returnurl", "http://139.226.64.38/v1.0/paymentchannel/topup/elong/notify_call");		
		//返回地址
		requestEntity.add("mobile", "1");
		//返回地址
		requestEntity.add("goform", "true");
		log.info("sendurl===="+sendurl);
		log.info("requestEntity====="+requestEntity);
		String result = restTemplate.postForObject(sendurl, requestEntity, String.class);
		url = java.net.URLDecoder.decode(urlhtml(result),"utf-8");
		System.out.println(url);
		} catch (Exception e) {
			log.error("请求支付出错啦！！！");
			map.put("resp_code", "failed");
			map.put("channel_type", "elong");
			map.put("resp_message", "亲,出现异常啦,再试一次吧");
			return map;
		}
		
		if(null!=url&&!"".equals(url)){
			map.put("resp_code", "success");
			map.put("channel_type", "elong");
			map.put("result", url);
			return map;
		}else{
			map.put("resp_code", "failed");
			map.put("channel_type", "elong");
			map.put("resp_message", "亲,失败了哦,再试一次吧");
			return map;
		}
		

	}
	
	
	private static String urlhtml(String html){
		try {
			
			html=html.substring(html.indexOf("data=")+5, html.indexOf("'/>"));
			
		} catch (Exception e) {
			
			
		}
		
		return html;
	}
	
	
	 private static String MD5(String sourceStr) {
	        String result = "";
	        try {
	            MessageDigest md = MessageDigest.getInstance("MD5");
	            md.update(sourceStr.getBytes());
	            byte b[] = md.digest();
	            int i;
	            StringBuffer buf = new StringBuffer("");
	            for (int offset = 0; offset < b.length; offset++) {
	                i = b[offset];
	                if (i < 0)
	                    i += 256;
	                if (i < 16)
	                    buf.append("0");
	                buf.append(Integer.toHexString(i));
	            }
	            result = buf.toString();
	            System.out.println("MD5(" + sourceStr + ",32) = " + result);
	            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
	        } catch (NoSuchAlgorithmException e) {
	            System.out.println(e);
	        }
	        return result;
	    }
	
	
}
